import json
import re

from django.contrib.auth import login
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.shortcuts import render

from apps.OrderInfos.models import OrderGoods, OrderInfo
from utils.views import LoginRequiredJsonMixin
# Create your views here.
from django.views import View
from apps.products.models import Product
from apps.administrators.models import Administrator


class GetAllGoodsView(View):
    """获取所有商品"""
    def get(self, request):
        page = request.GET.get('page')
        page_size = request.GET.get('page_size')
        ordering = request.GET.get('ordering')
        products = Product.objects.filter(is_delete=False).order_by(ordering)
        paginator = Paginator(products, per_page=page_size)
        # 获取指定页面的数据
        page_goods = paginator.page(page)
        goods_list = []
        for product in page_goods.object_list:
            goods_list.append({
                "id": product.product_id,
                'name': product.product_name,
                'price': product.price,
                'image_url': product.img_url,
                'descript': product.description,
                'stock': product.num,
                'type': Product.objects.get(product_id=product.product_id).type.type,
                'source': Product.objects.get(product_id=product.product_id).merchant.merchant_name
            })
        total_count = paginator.num_pages
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'goods_list': goods_list, 'count': total_count})


class RemoveProductView(View):
    """下架商品"""

    def put(self, request):
        data = json.loads(request.body.decode())
        product_id = data.get('id')
        try:
            product = Product.objects.get(product_id=product_id, is_delete=False)
        except Product.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '该商品不存在'})
        product.is_delete = True
        product.save()
        return JsonResponse({'code': 0, 'errmsg': '下架成功'})


class AdminLoginView(View):
    """管理员登录"""
    def post(self, request):
        data = json.loads(request.body.decode())
        account = data.get('account')
        password = data.get('password')
        if not all([account, password]):
            return JsonResponse({'code': 400, 'errmsg': '信息不全或账号不存在'})
        account_count = Administrator.objects.filter(account=account).count()
        pwd_count = Administrator.objects.filter(password=password).count()
        if account_count != 1 or pwd_count != 1:
            return JsonResponse({'code': 400, 'errmsg': '用户名或者密码为空'})
        else:
            admin = Administrator.objects.get(account=account, password=password)
        response = JsonResponse({'code': 0, 'errmsg': '登陆成功'})
        # login(request, admin)
        response.set_cookie('adminName', admin.account, max_age=60 * 60 * 24)
        return response


class AllOrderInfosView(View):
    """获取订单基本信息"""
    def get(self, request):
        page = request.GET.get('page')
        page_size = request.GET.get('page_size')
        ordering = request.GET.get('ordering')
        orders = OrderInfo.objects.filter(status=1, is_delete=False).order_by(ordering)
        if not orders:
            return JsonResponse({'code': 400, 'errmsg': '暂无需要配送的商品'})
        # 分页
        paginator = Paginator(orders, per_page=page_size)
        # 获取指定页面的数据
        page_orders = paginator.page(page)
        order_list = []
        for order in page_orders.object_list:
            order_list.append({
                'id': order.order_id,
                'amount': order.total_amount,
                'create_time': order.create_time,
                'pay_method': order.get_pay_method_display(),
                'status': order.get_status_display()
            })
        # 得到总页数
        total_num = paginator.num_pages
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'order_list': order_list, 'count': total_num})


class AllOrderGoodsView(View):
    """获取订单商品信息"""
    def get(self, request):
        order_id = request.GET.get('order_id')
        ordering = request.GET.get('ordering')
        product_list = []
        order_products = OrderGoods.objects.filter(order_id=order_id).order_by(ordering)
        for order_product in order_products:
            product_list.append({
                'count': order_product.count,
                'price': order_product.price,
                'name': order_product.product.product_name,
                'image_url': order_product.product.img_url
            })
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'order_good_list': product_list})


class ChangeStatusView(View):
    """修改订单状态"""
    def put(self,request):
        global order
        orders = OrderInfo.objects.filter(status=1, is_delete=False)
        if not orders:
            return JsonResponse({'code': 400, 'errmsg': '暂无要配送的商品'})
        for order in orders:
            order.status=3
            order.save()
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'status': order.get_status_display()})